//
//  FaceCollectionView.swift
//  NewWeiBo
//
//  Created by 吴天益 on 2017/8/2.
//  Copyright © 2017年 ttt. All rights reserved.
//

import UIKit
import SnapKit

class FaceCollectionView: UICollectionView,UICollectionViewDataSource,UICollectionViewDelegate {
    
    var linkageFaceSwithClusure: ((IndexPath)->())?
    
    let allArray = FaceViewModel.shareModel.allArray
    
    var pageControl: UIPageControl?
   
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.itemSize = CGSize(width: ScreenWidth, height: 180)
        
        flowLayout.scrollDirection = .horizontal
        
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        
        flowLayout.scrollDirection = .horizontal
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 界面设置
    func setupUI(){
        
        showsHorizontalScrollIndicator = false
        
        isPagingEnabled = true
        
        dataSource = self
        delegate = self
        
        //注册
        register(FaceCollectionCell.self, forCellWithReuseIdentifier: "face")
        
    }
    
    //MARK: - 拖动代理方法
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        
        //与按钮的联动
        
        let contentCenterX = scrollView.frame.size.width * 0.5 + scrollView.contentOffset.x
        let contentCenterY = scrollView.frame.size.height * 0.5
        let contentCenter = CGPoint(x: contentCenterX, y: contentCenterY)
        
        if let indexPath = self.indexPathForItem(at: contentCenter){
            
            if scrollView.isDragging || scrollView.isTracking || scrollView.isDecelerating{
                
                linkageFaceSwithClusure?(indexPath)
            }
            
            //联动分页控制器
            pageControl?.numberOfPages = FaceViewModel.shareModel.allArray[indexPath.section].count
            pageControl?.currentPage = indexPath.item
        }
        
    }
    
    //MARK: - 数据源
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return allArray.count
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return allArray[section].count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = dequeueReusableCell(withReuseIdentifier: "face", for: indexPath) as! FaceCollectionCell
        
        cell.faceArray = allArray[indexPath.section][indexPath.row]
        
        cell.indexPath = indexPath
        
        return cell
    }

}

//MARK:
//MARK: - 自定义cell
class FaceCollectionCell: UICollectionViewCell {
    
    var faceArray: [FaceModel]?{
        didSet{
            
            guard let arr = faceArray  else {
                return
            }
            
            for button in buttonArray{
                button.isHidden = true
            }
            
            for (i,model) in arr.enumerated(){
                
                //把faceArray里的模型数据赋值给按钮的属性
                buttonArray[i].faceModel = model
                
                buttonArray[i].isHidden = false
                //图片表情
                if model.type == "0"{
                    
                    let image = UIImage(named: model.path!, in: FaceViewModel.shareModel.bundle, compatibleWith: nil)
                    
                    buttonArray[i].setImage(image, for: .normal)
                    buttonArray[i].setTitle(nil, for: .normal)
                    
                }else{
                   //oc字符串转emoji表情
                    let emoji = (model.code! as NSString).emoji()
                    buttonArray[i].setTitle(emoji, for: .normal)
                    buttonArray[i].setImage(nil, for: .normal)
                }
                
            }
            
        }
    }
    
    var indexPath: IndexPath?{
        didSet{
            
            guard let iP = indexPath else {
                return
            }
            lable.text = "第\(iP.section)组,第\(iP.row)行"
        }
    }
    
    //按钮数组
    lazy var buttonArray: [FaceButton] = [FaceButton]()

    lazy var lable: UILabel = {
        let lable = UILabel()
        
        lable.font = UIFont.systemFont(ofSize: 20)
        lable.textColor = UIColor.blue
        lable.textAlignment = .center
    
        return lable
    }()
     
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 界面设置
    func setupUI(){
        backgroundColor = UIColor.white
        
        addChildButtons()
        addSubview(lable)
        
        lable.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
    }
    
    //MARK: - 添加20个按钮
    private func addChildButtons() {
        //  每项的宽度
        let buttonWidth:CGFloat = ScreenWidth / 7
        //  每项的高度
        let buttonHeight:CGFloat = 180 / 3
        
        for i in 0..<20 {
            //  计算列索引
            let colIndex:CGFloat = CGFloat(i % 7)
            //  计算行的索引
            let rowIndex:CGFloat = CGFloat(i / 7)
            
            let button = FaceButton()
            
            //  设置x，y
            button.frame.origin.x = colIndex * buttonWidth
            button.frame.origin.y = rowIndex * buttonHeight
            button.frame.size = CGSize(width: buttonWidth, height: buttonHeight)
            //  设置文字大小
            button.titleLabel?.font = UIFont.systemFont(ofSize: 33)
            contentView.addSubview(button)
            //  记录表情按钮
            buttonArray.append(button)
            
            //按钮点击事件
            button.addTarget(self, action: #selector(clickFaceButton(button:)), for: .touchUpInside)
        }
        
        //添加最后一个删除按钮
        let deleteButton = UIButton(frame: CGRect(x: bounds.size.width - buttonWidth, y: bounds.size.height - buttonHeight, width: buttonWidth, height: buttonHeight))
        
        deleteButton.setImage(UIImage(named: "compose_emotion_delete"), for: .normal)
        deleteButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), for: .highlighted)
        
        deleteButton.addTarget(self, action: #selector(clickDeleteButton(button:)), for: .touchUpInside)
        contentView.addSubview(deleteButton)
    }

    //MARK: - 图片按钮点击事件
    func clickFaceButton(button: FaceButton){
        
        //发送通知给textView赋值
        NotificationCenter.default.post(name: NSNotification.Name(AddFaceToTextView), object: button.faceModel)
    }
    
    //MARK: - 删除按钮点击事件
    func clickDeleteButton(button: UIButton){
        
        //发送删除通知
        NotificationCenter.default.post(name: NSNotification.Name(DeleteContentOfTextView), object: nil)
    }
    
    
    
    
}

//MARK: - 自定义按钮,记录模型数据
class FaceButton: UIButton {
    
    var faceModel: FaceModel?
    
    
}



